//
// Created by xm on 2024/4/6.
//


#include "iostream"
#include "Test02.h"

using namespace std;

void func1(int &a){
    a *= 10;
}

void  demo1()
{
    int a = 10;
    int& b= a;

    b = 100;

    cout << a << endl;

    // 函数引用的方式传参
    func1(a);
    cout << a << endl;



}

void demo2()
{
    int a = 10;
    int& b = a;

    b = 100;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    cout << "------------" << endl;
    //一个变量可以有n个别名
    int& c = a;
    c = 200;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    cout << "c:" << c << endl;
    cout << "------------" << endl;
    //a,b,c的地址都是相同的
    cout << "a:" << &a << endl;
    cout << "b:" << &b << endl;
    cout << "c:" << &c << endl;
}

void demo3(){
    //1) 引用必须初始化
    //int& ref; //报错:必须初始化引用
    //2) 引用一旦初始化，不能改变引用
    int a = 10;
    int b = 20;
    int& ref = a;
    ref = b; //不能改变引用，只是给a赋值
}

void demo4(){
    // 数组引用
    int arr[] = {1,2 ,3,4,5};
    // 第一种
    typedef int (MY_ARR)[5];
    MY_ARR &r1 = arr;

    // 第二种 推荐
    int (&r2)[5] = arr;

    // 第三种
    typedef  int(&MY_ARR2)[5];

    MY_ARR2 r3 = arr;


    for (int i = 0; i < 5; ++i) {
        cout << r2[i] << endl;
    }
}

struct Teacher{
    int mAge;
};
//指针间接修改teacher的年龄
void AllocateAndInitByPointer(Teacher* teacher){

    teacher->mAge = 200;
}
//引用修改teacher年龄
void AllocateAndInitByReference(Teacher*& teacher){
    teacher->mAge = 300;
}
void demo5(){
    //创建Teacher
    Teacher* teacher = (Teacher*)malloc(sizeof(Teacher) );


    //指针间接赋值
    AllocateAndInitByPointer(teacher);
    cout << "AllocateAndInitByPointer:" << teacher->mAge << endl;
    //引用赋值,将teacher本身传到ChangeAgeByReference函数中
    AllocateAndInitByReference(teacher);
    cout << "AllocateAndInitByReference:" << teacher->mAge << endl;
//    free(tp);
    free(teacher);

}
// 指针的引用
void demo6()
{
    char * p = "翠花";
    char * &p1 = p;
    char ** p2 = &p;

    printf("p %p %s \n", p, p);
    printf("p1 %p %s \n", p1,  p1);
    printf("p2 %p %s \n", p2, *p2);



    int  a = 10;
    int * ap1 = &a;
    int ** ap2 = &ap1;
    int * &ap3 = ap1;
    int &ap4 = a;

    printf("a %p %d\n", &a, a);
    printf("ap1 %p %p %d \n", &ap1, ap1 , *ap1);
    printf("ap2 %p %p %p \n", &ap2, ap2, *ap2);
    printf("ap3 %p %p \n", &ap3, ap3 );
    printf("ap4 %p %d \n", &ap4, ap4 );

//    *ap2 = 20;
//    printf("a %d\n", a);
}

void  test02()
{
//    demo4();


    demo6();

}



